package com.study.concurrent.A_ThreadManagement.d_ControlThreadInterrupt;

import java.io.File;

/**
 * Created by 赵超 on 2017/3/18.
 */
public class FileSearch implements Runnable {
    private String initPath;
    private String fileName;

    public FileSearch(String initPath, String fileName) {
        this.initPath = initPath;
        this.fileName = fileName;
    }

    @Override
    public void run() {
        File file = new File(initPath);
        if (file.isDirectory()) {
            try {
                directoryProcess(file);
            } catch (InterruptedException e) {
                System.out.printf("%s : The Search has been interrupted\n",
                        Thread.currentThread().getName());
            }
        }
    }

    /**
     * 提取目录中的所有文件对象并传入fileProcess方法
     *
     * @param file
     * @throws InterruptedException
     */
    private void directoryProcess(File file) throws InterruptedException {
        File[] files = file.listFiles();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    directoryProcess(files[i]);
                } else {
                    fileProcess(files[i]);
                }
            }
        }
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
    }

    /**
     * 查看传入文件是否为需要查找的文件，是就打印文件绝对路径
     *
     * @param file
     * @throws InterruptedException
     */
    private void fileProcess(File file) throws InterruptedException {
        if (file.getName().equals(fileName)) {
            System.out.printf("%s : %s\n", Thread.currentThread().getName(), file.getAbsoluteFile());
        }
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
    }
}
